import re

from main.models import Book
import pdfplumber


def get_book(request, slug):

    """ Получаем книгу """

    def _convert_to_desired_view(text):
        text = text[::-1]
        current_page = ''
        text = re.sub('^\d{,5}?\n', '', text)
        return (text[::-1], current_page)

    def _get_authors_name(book):
        full_name = book.author.name.split()
        name = full_name[0][0] + '. '
        surname = full_name[1]
        return name + surname

    def _get_right_pages(request, book):
        current_page = int(request.GET.get('page'))
        total_pages = book.volume
        previous_page = current_page -1 if (current_page -1) >= 0 else False
        next_page = current_page + 1
        return {'current_page': current_page,
                'total_pages': total_pages,
                'next_page': next_page,
                'previous_page': previous_page}

    def _get_context(request, slug, book):
        page_number = int(request.GET.get('page'))
        pages = _get_right_pages(request, book)
        path_to_book = book.file.path
        authors_name = _get_authors_name(book)
        context = {'page_number': page_number,
                   'author': book.author.name,
                   'title': book.title,
                   'book_slug': book.slug,
                   'is_favorites': book.is_favorites,
                   'bookmark': book.bookmark,
                   **pages}
        with pdfplumber.open(path_to_book) as file:
            page = file.pages[page_number]
            text, current_page = _convert_to_desired_view(page.extract_text())
            context['text'] = text

        return context


    # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    book = Book.objects.get(slug=slug)

    if request.GET.get('page'):
        template = 'main/contents_of_book.html'
        context = _get_context(request, slug, book)
        return (template, context)

    else:
        template = 'main/book_big.html'
        context = {'book': book}
        return (template, context)


def get_list_of_books():

    """ Получаем список книг в нужном виде """

    def get_title(book):
        modified_book = book[0].split()
        if len(modified_book) > 4: return ' '.join(modified_book[:4]) + '...'
        else: return book[0]

    def get_description(book):
        return ' '.join(book[1].split()[:25]) + '...'


    # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    result = []
    books = Book.objects.values_list('title', 'description', 'slug', 'image').all()

    for book in books:
        title = get_title(book)
        description = get_description(book)

        result.append({'title': title, 'description': description, 'slug': book[2], 'image': book[3]})

    return result


def add_bookmark(request, book, action, page):

    """ Добавляем в закладку страницу """

    book_orm = Book.objects.get(slug=book)

    if action == 'add':
        book_orm.bookmark = page
        book_orm.save()
    elif action == 'remove':
        book_orm.bookmark = 0
        book_orm.save()


def add_last_page(request, book, page_number):

    book = Book.objects.get(slug=book)
    book.last_page = page_number
    book.save()


def get_information_about_book(request, slug):

    """ Получаем информацию о книге """

    book = Book.objects.get(slug=slug)
    context = {'last_page': book.last_page,
               'volume': book.volume,
               'favorites': book.is_favorites}
    return context


def action_favorites(book, action):

    """ Выполняем какое-то действие с закладкой """

    book = Book.objects.get(slug=book)

    if action == 'remove_favorites':
        book.is_favorites = False
    elif action == 'add_favorites':
        book.is_favorites = True

    book.save()
